package com.taobao.askwho.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.taobao.askwho.ao.ComplexAo;
import com.taobao.askwho.ao.TagAo;
import com.taobao.askwho.po.TagMemory;
import com.taobao.askwho.po.UserInfo;
import com.taobao.askwho.utils.ToolUtil;
import com.taobao.askwho.utils.session.SessionUtil;
import com.taobao.askwho.vo.PersonalPageRecordVo;
import com.taobao.askwho.vo.ResultPo;

@Controller                 
@RequestMapping("/tagopt.do")
public class TagAction extends BaseAction {
	@RequestMapping(params = "method=deleteByTagUuids")
	public void deleteByTagUuids(String tagUuids, String type, HttpServletResponse response){
		final ResultPo po = new ResultPo();
		po.setMsg("");
		po.setSuccess(true);

		if(tagUuids == null || tagUuids.trim().equals("")) {
			po.setMsg("tag id is null");
			po.setSuccess(false);
		} else {
			List<String> list = Arrays.asList(tagUuids.split(","));
			Set<String> uuidSet = new HashSet<String>(list);
			try {
				if(type.equals("url")) {
					TagAo.get().deleteUrlByTagUuid(uuidSet);					
				} else if(type.equals("person")) {
					TagAo.get().deletePersonByTagUuid(uuidSet);
				} else {
					po.setMsg("type is not url or person");
					po.setSuccess(true);
				}
				TagAo.get().deleteTagRelationByUuid(uuidSet);
			} catch (SQLException e) {
				po.setMsg("删除"+ type + "异常->" + e.toString());
				po.setSuccess(false);
			}
		}

		try {
			this.writeJSONToResponseJSONObject(response, po);
		} catch (IOException e) {
			logger.error("", e);
		}
	}

	@RequestMapping(params = "method=collectOtherTags")
	public String collectOtherTags(String myUuid, String otherUuid, HttpServletResponse response){
		// myUuid, String otherUuid
		ComplexAo.get().collectOtherTags(myUuid,otherUuid);
		return "redirect:/urljump.do?method=gotoPersonPage&userUuid=" + myUuid;
	}	

	//收藏一个Tag
	@RequestMapping(params = "method=collectATag")
	public void collectATag(HttpServletRequest request, String tagUuid, HttpServletResponse response) {
		UserInfo user = SessionUtil.getUserInfo(request);
		
		final ResultPo po = new ResultPo();
		po.setMsg("");
		po.setSuccess(true);
		
		if(user == null) {
			po.setMsg("请先登录");
			po.setSuccess(false);			
		} else {
			String userUuid = user.getUuid();
			List<String> list = new ArrayList<String>();
			list.add(tagUuid);
			List<PersonalPageRecordVo> resultList = ComplexAo.get().findResultByUuids(list);
			if(resultList == null || resultList.size() == 0) {
				po.setMsg("收藏的条目可能已被删除->" + tagUuid);
				po.setSuccess(false);
			} else {
				try {
					PersonalPageRecordVo vo = resultList.get(0);
					if (vo.getType().equals("person")) {
						ComplexAo.get().addNewPerson(
								vo.getPersonInfo().getPersonName(), vo.isPublic(),
								vo.getPersonInfo().getWangwang(),
								vo.getTagNamesSet().toArray(new String[0]),
								userUuid);
					} else if (vo.getType().equals("url")) {
						ComplexAo.get().addNewUrl(vo.getUrlInfo().getUrlContent(),
								vo.isPublic(),
								vo.getTagNamesSet().toArray(new String[0]),
								userUuid);
					} else {
						po.setMsg("Tag查询结果type不对->" + vo.getType());
						po.setSuccess(false);
					}
				} catch (Exception e) {
					logger.error("添加Tag时错误!", e);
				}
			}
		}
		try {
			this.writeJSONToResponseJSONObject(response, po);
		} catch (IOException e) {
			logger.error("", e);
		}
	}	
	//自动提示tag
	@RequestMapping(params = "method=tagAutoCompleted")
	public void tagAutoCompleted(String q, String callback, HttpServletResponse response) {
		try {
			q = URLDecoder.decode(q, "utf-8");
		} catch (UnsupportedEncodingException e1) {
			logger.error("", e1);
		}
		List<TagMemory> list = TagAo.get().queryTagMemoryListLike(q);
		for(TagMemory po : list) {
			po.setName(po.getTagName());
			po.setId(po.getTagName());
		}
		JSONArray array = JSONArray.fromObject(list);
		String responseString = "";
		if(callback == null) {
			responseString = array.toString();	
		} else {
			responseString = ToolUtil.addCallBackString(array.toString(), callback);	
		}
		System.out.println(responseString);
		System.out.println(callback);
		this.writeHTMLToResponse(responseString, response);
	}
}
